import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Admins } from '../../entities/Admins.entity'
import { encryptPassword, verifyPassword } from '../../utils/cryptoUtils'

@Provide()
export class AdminsService {
  @InjectEntityModel(Admins)
  repo!: Repository<Admins>

  async list(page: number = 1, pageSize: number = 10) {
    const [data, total] = await this.repo.findAndCount({
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' } // 可选排序
    })

    return {
      total,
      items: data,
    }
  }

  async add(data: Partial<Admins>) {
    // 密码要加密
    if (data.password) {
      data.password = await encryptPassword(data.password)
    }
    const obj = this.repo.create(data)
    return this.repo.save(obj)
  }

  async edit(data: Partial<Admins>) {
    // 密码要加密
    if (data.password) {
      data.password = await encryptPassword(data.password)
    }
    return this.repo.save(data)
  }

  async delete(id: number) {
    return this.repo.delete(id)
  }

  // 登录
  async login(data: any) {
    const admin = await this.repo.findOne({
      where: { phone: data.username },
    })
    if (admin){
      if (!(await verifyPassword(data.password, admin?.password || ''))) {
        throw new Error('密码错误')
        // return admin
      }
      return admin
    }
    if (!admin) {
      throw new Error('管理员不存在')
    }
  }

  // 登出
  async logout() {
    // 直接返回成功
    return {
      code: 200,
      message: '登出成功',
      data: null
    }
  }
}
